import numpy as np
import tensorflow.compat.v2 as tf
tf.enable_v2_behavior()
import pandas as pd
from tensorflow import keras
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import RobustScaler
from sklearn.preprocessing import MinMaxScaler
from matplotlib import pyplot
import plotly.graph_objects as go
import math
import seaborn as sns
from sklearn.metrics import mean_squared_error
np.random.seed(1)
tf.random.set_seed(1)
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, GRU, Dropout, RepeatVector, TimeDistributed
from keras import backend
MODELFILENAME = 'MODELS/GRU_1h_TFM'
TIME_STEPS=6 #1h
CMODEL = GRU
MODEL = "GRU"
UNITS=55
DROPOUT=0.118
ACTIVATION='tanh'
OPTIMIZER='adam'
EPOCHS=36
BATCHSIZE=9
VALIDATIONSPLIT=0.2
# Code to read csv file into Colaboratory:
# from google.colab import files
# uploaded = files.upload()
# import io
# df = pd.read_csv(io.BytesIO(uploaded['SentDATA.csv']))
# Dataset is now stored in a Pandas Dataframe
df = pd.read_csv('../../data/dadesTFM.csv')
df.reset_index(inplace=True)
df['Time'] = pd.to_datetime(df['Time'])
df = df.set_index('Time')
columns = ['PM1','PM25','PM10','PM1ATM','PM25ATM','PM10ATM']
df1 = df.copy();
df1 = df1.rename(columns={"PM 1":"PM1","PM 2.5":"PM25","PM 10":"PM10","PM 1 ATM":"PM1ATM","PM 2.5 ATM":"PM25ATM","PM 10 ATM":"PM10ATM"})
df1['PM1'] = df['PM 1'].astype(np.float32)
df1['PM25'] = df['PM 2.5'].astype(np.float32)
df1['PM10'] = df['PM 10'].astype(np.float32)
df1['PM1ATM'] = df['PM 1 ATM'].astype(np.float32)
df1['PM25ATM'] = df['PM 2.5 ATM'].astype(np.float32)
df1['PM10ATM'] = df['PM 10 ATM'].astype(np.float32)
df2 = df1.copy()
train_size = int(len(df2) * 0.8)
test_size = len(df2) - train_size
train, test = df2.iloc[0:train_size], df2.iloc[train_size:len(df2)]
train.shape, test.shape
((3117, 7), (780, 7))
#Standardize the data
for col in columns:
scaler = StandardScaler()
train[col] = scaler.fit_transform(train[[col]])
<ipython-input-6-83cecdbc25f8>:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy train[col] = scaler.fit_transform(train[[col]]) <ipython-input-6-83cecdbc25f8>:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy train[col] = scaler.fit_transform(train[[col]]) <ipython-input-6-83cecdbc25f8>:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy train[col] = scaler.fit_transform(train[[col]]) <ipython-input-6-83cecdbc25f8>:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy train[col] = scaler.fit_transform(train[[col]]) <ipython-input-6-83cecdbc25f8>:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy train[col] = scaler.fit_transform(train[[col]]) <ipython-input-6-83cecdbc25f8>:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy train[col] = scaler.fit_transform(train[[col]])
def create_sequences(X, y, time_steps=TIME_STEPS):
Xs, ys = [], []
for i in range(len(X)-time_steps):
Xs.append(X.iloc[i:(i+time_steps)].values)
ys.append(y.iloc[i+time_steps])
return np.array(Xs), np.array(ys)
X_train, y_train = create_sequences(train[[columns[1]]], train[columns[1]])
#X_test, y_test = create_sequences(test[[columns[1]]], test[columns[1]])
print(f'X_train shape: {X_train.shape}')
print(f'y_train shape: {y_train.shape}')
X_train shape: (3111, 6, 1) y_train shape: (3111,)
#afegir nova mètrica
def rmse(y_true, y_pred):
return backend.sqrt(backend.mean(backend.square(y_pred - y_true), axis=-1))
model = Sequential()
model.add(CMODEL(units = UNITS, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(Dropout(rate=DROPOUT))
model.add(TimeDistributed(Dense(1,kernel_initializer='normal',activation=ACTIVATION)))
model.compile(optimizer=OPTIMIZER, loss='mae',metrics=['mse',rmse])
model.summary()
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= gru (GRU) (None, 6, 55) 9570 _________________________________________________________________ dropout (Dropout) (None, 6, 55) 0 _________________________________________________________________ time_distributed (TimeDistri (None, 6, 1) 56 ================================================================= Total params: 9,626 Trainable params: 9,626 Non-trainable params: 0 _________________________________________________________________
history = model.fit(X_train, y_train, epochs=EPOCHS, batch_size=BATCHSIZE, validation_split=VALIDATIONSPLIT,
callbacks=[keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, mode='min')], shuffle=False)
Epoch 1/36 277/277 [==============================] - 1s 5ms/step - loss: 0.4384 - mse: 0.4318 - rmse: 0.4684 - val_loss: 0.2538 - val_mse: 0.2411 - val_rmse: 0.2951 Epoch 2/36 277/277 [==============================] - 1s 3ms/step - loss: 0.3618 - mse: 0.3334 - rmse: 0.3863 - val_loss: 0.2255 - val_mse: 0.2257 - val_rmse: 0.2488 Epoch 3/36 277/277 [==============================] - 1s 3ms/step - loss: 0.3507 - mse: 0.3227 - rmse: 0.3735 - val_loss: 0.2176 - val_mse: 0.2224 - val_rmse: 0.2363 Epoch 4/36 277/277 [==============================] - 1s 3ms/step - loss: 0.3473 - mse: 0.3191 - rmse: 0.3704 - val_loss: 0.2161 - val_mse: 0.2226 - val_rmse: 0.2343 Epoch 5/36 277/277 [==============================] - 1s 3ms/step - loss: 0.3460 - mse: 0.3183 - rmse: 0.3695 - val_loss: 0.2154 - val_mse: 0.2227 - val_rmse: 0.2334 Epoch 6/36 277/277 [==============================] - 1s 3ms/step - loss: 0.3452 - mse: 0.3171 - rmse: 0.3686 - val_loss: 0.2153 - val_mse: 0.2237 - val_rmse: 0.2339 Epoch 7/36 277/277 [==============================] - 1s 3ms/step - loss: 0.3445 - mse: 0.3170 - rmse: 0.3682 - val_loss: 0.2151 - val_mse: 0.2227 - val_rmse: 0.2332 Epoch 8/36 277/277 [==============================] - 1s 3ms/step - loss: 0.3432 - mse: 0.3160 - rmse: 0.3669 - val_loss: 0.2145 - val_mse: 0.2233 - val_rmse: 0.2330 Epoch 9/36 277/277 [==============================] - 1s 3ms/step - loss: 0.3423 - mse: 0.3158 - rmse: 0.3661 - val_loss: 0.2149 - val_mse: 0.2226 - val_rmse: 0.2334 Epoch 10/36 277/277 [==============================] - 1s 3ms/step - loss: 0.3415 - mse: 0.3150 - rmse: 0.3654 - val_loss: 0.2142 - val_mse: 0.2228 - val_rmse: 0.2331 Epoch 11/36 277/277 [==============================] - 1s 3ms/step - loss: 0.3412 - mse: 0.3152 - rmse: 0.3651 - val_loss: 0.2127 - val_mse: 0.2221 - val_rmse: 0.2315 Epoch 12/36 277/277 [==============================] - 1s 3ms/step - loss: 0.3402 - mse: 0.3144 - rmse: 0.3640 - val_loss: 0.2126 - val_mse: 0.2222 - val_rmse: 0.2315 Epoch 13/36 277/277 [==============================] - 1s 3ms/step - loss: 0.3396 - mse: 0.3145 - rmse: 0.3635 - val_loss: 0.2119 - val_mse: 0.2211 - val_rmse: 0.2304 Epoch 14/36 277/277 [==============================] - 1s 3ms/step - loss: 0.3390 - mse: 0.3138 - rmse: 0.3629 - val_loss: 0.2124 - val_mse: 0.2218 - val_rmse: 0.2312 Epoch 15/36 277/277 [==============================] - 1s 3ms/step - loss: 0.3384 - mse: 0.3140 - rmse: 0.3622 - val_loss: 0.2111 - val_mse: 0.2207 - val_rmse: 0.2298 Epoch 16/36 277/277 [==============================] - 1s 3ms/step - loss: 0.3379 - mse: 0.3135 - rmse: 0.3614 - val_loss: 0.2109 - val_mse: 0.2206 - val_rmse: 0.2291 Epoch 17/36 277/277 [==============================] - 1s 4ms/step - loss: 0.3371 - mse: 0.3127 - rmse: 0.3604 - val_loss: 0.2110 - val_mse: 0.2206 - val_rmse: 0.2295 Epoch 18/36 277/277 [==============================] - 1s 3ms/step - loss: 0.3368 - mse: 0.3125 - rmse: 0.3600 - val_loss: 0.2104 - val_mse: 0.2201 - val_rmse: 0.2284 Epoch 19/36 277/277 [==============================] - 1s 3ms/step - loss: 0.3366 - mse: 0.3122 - rmse: 0.3594 - val_loss: 0.2103 - val_mse: 0.2198 - val_rmse: 0.2284 Epoch 20/36 277/277 [==============================] - 1s 3ms/step - loss: 0.3359 - mse: 0.3118 - rmse: 0.3586 - val_loss: 0.2094 - val_mse: 0.2195 - val_rmse: 0.2270 Epoch 21/36 277/277 [==============================] - 1s 4ms/step - loss: 0.3356 - mse: 0.3115 - rmse: 0.3582 - val_loss: 0.2091 - val_mse: 0.2195 - val_rmse: 0.2270 Epoch 22/36 277/277 [==============================] - 1s 4ms/step - loss: 0.3349 - mse: 0.3114 - rmse: 0.3573 - val_loss: 0.2096 - val_mse: 0.2194 - val_rmse: 0.2270 Epoch 23/36 277/277 [==============================] - 1s 3ms/step - loss: 0.3347 - mse: 0.3111 - rmse: 0.3570 - val_loss: 0.2084 - val_mse: 0.2191 - val_rmse: 0.2264 Epoch 24/36 277/277 [==============================] - 1s 4ms/step - loss: 0.3348 - mse: 0.3113 - rmse: 0.3569 - val_loss: 0.2088 - val_mse: 0.2195 - val_rmse: 0.2262 Epoch 25/36 277/277 [==============================] - 1s 4ms/step - loss: 0.3349 - mse: 0.3111 - rmse: 0.3571 - val_loss: 0.2092 - val_mse: 0.2199 - val_rmse: 0.2265 Epoch 26/36 277/277 [==============================] - 1s 5ms/step - loss: 0.3344 - mse: 0.3109 - rmse: 0.3565 - val_loss: 0.2079 - val_mse: 0.2191 - val_rmse: 0.2255 Epoch 27/36 277/277 [==============================] - 1s 4ms/step - loss: 0.3347 - mse: 0.3112 - rmse: 0.3566 - val_loss: 0.2081 - val_mse: 0.2190 - val_rmse: 0.2255 Epoch 28/36 277/277 [==============================] - 1s 4ms/step - loss: 0.3337 - mse: 0.3106 - rmse: 0.3560 - val_loss: 0.2076 - val_mse: 0.2189 - val_rmse: 0.2255 Epoch 29/36 277/277 [==============================] - 1s 4ms/step - loss: 0.3346 - mse: 0.3110 - rmse: 0.3567 - val_loss: 0.2075 - val_mse: 0.2190 - val_rmse: 0.2250 Epoch 30/36 277/277 [==============================] - 1s 5ms/step - loss: 0.3339 - mse: 0.3108 - rmse: 0.3560 - val_loss: 0.2078 - val_mse: 0.2190 - val_rmse: 0.2252 Epoch 31/36 277/277 [==============================] - 1s 4ms/step - loss: 0.3337 - mse: 0.3105 - rmse: 0.3560 - val_loss: 0.2069 - val_mse: 0.2188 - val_rmse: 0.2249 Epoch 32/36 277/277 [==============================] - 1s 4ms/step - loss: 0.3336 - mse: 0.3110 - rmse: 0.3554 - val_loss: 0.2073 - val_mse: 0.2185 - val_rmse: 0.2246 Epoch 33/36 277/277 [==============================] - 1s 4ms/step - loss: 0.3333 - mse: 0.3102 - rmse: 0.3552 - val_loss: 0.2074 - val_mse: 0.2188 - val_rmse: 0.2251 Epoch 34/36 277/277 [==============================] - 1s 4ms/step - loss: 0.3336 - mse: 0.3104 - rmse: 0.3553 - val_loss: 0.2076 - val_mse: 0.2190 - val_rmse: 0.2250 Epoch 35/36 277/277 [==============================] - 1s 4ms/step - loss: 0.3334 - mse: 0.3106 - rmse: 0.3552 - val_loss: 0.2072 - val_mse: 0.2189 - val_rmse: 0.2245 Epoch 36/36 277/277 [==============================] - 1s 5ms/step - loss: 0.3333 - mse: 0.3104 - rmse: 0.3552 - val_loss: 0.2061 - val_mse: 0.2182 - val_rmse: 0.2238
import matplotlib.pyplot as plt
plt.plot(history.history['loss'], label='MAE Training loss')
plt.plot(history.history['val_loss'], label='MAE Validation loss')
plt.plot(history.history['mse'], label='MSE Training loss')
plt.plot(history.history['val_mse'], label='MSE Validation loss')
plt.plot(history.history['rmse'], label='RMSE Training loss')
plt.plot(history.history['val_rmse'], label='RMSE Validation loss')
plt.legend();
X_train_pred = model.predict(X_train, verbose=0)
train_mae_loss = np.mean(np.abs(X_train_pred - X_train), axis=1)
plt.hist(train_mae_loss, bins=50)
plt.xlabel('Train MAE loss')
plt.ylabel('Number of Samples');
def evaluate_prediction(predictions, actual, model_name):
errors = predictions - actual
mse = np.square(errors).mean()
rmse = np.sqrt(mse)
mae = np.abs(errors).mean()
print(model_name + ':')
print('Mean Absolute Error: {:.4f}'.format(mae))
print('Root Mean Square Error: {:.4f}'.format(rmse))
print('Mean Square Error: {:.4f}'.format(mse))
print('')
return mae,rmse,mse
mae,rmse,mse = evaluate_prediction(X_train_pred, X_train,MODEL)
GRU: Mean Absolute Error: 0.1944 Root Mean Square Error: 0.4310 Mean Square Error: 0.1857
model.save(MODELFILENAME+'.h5')
#càlcul del threshold de test
def calculate_threshold(X_test, X_test_pred):
distance = np.sqrt(np.mean(np.square(X_test_pred - X_test),axis=1))
"""Sorting the scores/diffs and using a 0.80 as cutoff value to pick the threshold"""
distance.sort();
cut_off = int(0.9 * len(distance));
threshold = distance[cut_off];
return threshold
for col in columns:
print ("####################### "+col +" ###########################")
#Standardize the test data
scaler = StandardScaler()
test_cpy = test.copy()
test[col] = scaler.fit_transform(test[[col]])
#creem seqüencia amb finestra temporal per les dades de test
X_test1, y_test1 = create_sequences(test[[col]], test[col])
print(f'Testing shape: {X_test1.shape}')
#evaluem el model
eval = model.evaluate(X_test1, y_test1)
print("evaluate: ",eval)
#predim el model
X_test1_pred = model.predict(X_test1, verbose=0)
evaluate_prediction(X_test1_pred, X_test1,MODEL)
#càlcul del mae_loss
test1_mae_loss = np.mean(np.abs(X_test1_pred - X_test1), axis=1)
test1_rmse_loss = np.sqrt(np.mean(np.square(X_test1_pred - X_test1),axis=1))
# reshaping test prediction
X_test1_predReshape = X_test1_pred.reshape((X_test1_pred.shape[0] * X_test1_pred.shape[1]), X_test1_pred.shape[2])
# reshaping test data
X_test1Reshape = X_test1.reshape((X_test1.shape[0] * X_test1.shape[1]), X_test1.shape[2])
threshold_test = calculate_threshold(X_test1Reshape,X_test1_predReshape)
test1_score_df = pd.DataFrame(test[TIME_STEPS:])
test1_score_df['loss'] = test1_rmse_loss.reshape((-1))
test1_score_df['threshold'] = threshold_test
test1_score_df['anomaly'] = test1_score_df['loss'] > test1_score_df['threshold']
test1_score_df[col] = test[TIME_STEPS:][col]
#gràfic test lost i threshold
fig = go.Figure()
fig.add_trace(go.Scatter(x=test1_score_df.index, y=test1_score_df['loss'], name='Test loss'))
fig.add_trace(go.Scatter(x=test1_score_df.index, y=test1_score_df['threshold'], name='Threshold'))
fig.update_layout(showlegend=True, title='Test loss vs. Threshold')
fig.show()
#Posem les anomalies en un array
anomalies1 = test1_score_df.loc[test1_score_df['anomaly'] == True]
anomalies1.shape
print('anomalies: ',anomalies1.shape); print();
#Gràfic dels punts i de les anomalíes amb els valors de dades transformades per verificar que la normalització que s'ha fet no distorssiona les dades
fig = go.Figure()
fig.add_trace(go.Scatter(x=test1_score_df.index, y=scaler.inverse_transform(test1_score_df[col]), name=col))
fig.add_trace(go.Scatter(x=anomalies1.index, y=scaler.inverse_transform(anomalies1[col]), mode='markers', name='Anomaly'))
fig.update_layout(showlegend=True, title='Detected anomalies')
fig.show()
print ("######################################################")
####################### PM1 ###########################
<ipython-input-17-e1f1d6df3b5c>:8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy test[col] = scaler.fit_transform(test[[col]])
Testing shape: (774, 6, 1) 25/25 [==============================] - 0s 1ms/step - loss: 0.3882 - mse: 0.6123 - rmse: 0.4214 evaluate: [0.3882055878639221, 0.6122729778289795, 0.42144301533699036] GRU: Mean Absolute Error: 0.2024 Root Mean Square Error: 0.5881 Mean Square Error: 0.3458
anomalies: (118, 10)
###################################################### ####################### PM25 ########################### Testing shape: (774, 6, 1)
<ipython-input-17-e1f1d6df3b5c>:8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
25/25 [==============================] - 0s 1ms/step - loss: 0.3992 - mse: 0.5478 - rmse: 0.4338 evaluate: [0.3992084562778473, 0.5477511286735535, 0.43379801511764526] GRU: Mean Absolute Error: 0.2082 Root Mean Square Error: 0.5456 Mean Square Error: 0.2976
anomalies: (95, 10)
###################################################### ####################### PM10 ########################### Testing shape: (774, 6, 1)
<ipython-input-17-e1f1d6df3b5c>:8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
25/25 [==============================] - 0s 1ms/step - loss: 0.4080 - mse: 0.5181 - rmse: 0.4438 evaluate: [0.40803614258766174, 0.5181261301040649, 0.44384434819221497] GRU: Mean Absolute Error: 0.2120 Root Mean Square Error: 0.5080 Mean Square Error: 0.2581
anomalies: (91, 10)
###################################################### ####################### PM1ATM ########################### Testing shape: (774, 6, 1)
<ipython-input-17-e1f1d6df3b5c>:8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
25/25 [==============================] - 0s 1ms/step - loss: 0.4085 - mse: 0.5499 - rmse: 0.4454 evaluate: [0.40848925709724426, 0.5498854517936707, 0.4453986585140228] GRU: Mean Absolute Error: 0.2053 Root Mean Square Error: 0.5015 Mean Square Error: 0.2515
anomalies: (93, 10)
###################################################### ####################### PM25ATM ########################### Testing shape: (774, 6, 1)
<ipython-input-17-e1f1d6df3b5c>:8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
25/25 [==============================] - 0s 2ms/step - loss: 0.4056 - mse: 0.5584 - rmse: 0.4422 evaluate: [0.4055670499801636, 0.5584157109260559, 0.44218432903289795] GRU: Mean Absolute Error: 0.2046 Root Mean Square Error: 0.5136 Mean Square Error: 0.2638
anomalies: (93, 10)
###################################################### ####################### PM10ATM ########################### Testing shape: (774, 6, 1)
<ipython-input-17-e1f1d6df3b5c>:8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
25/25 [==============================] - 0s 2ms/step - loss: 0.4062 - mse: 0.5334 - rmse: 0.4418 evaluate: [0.4061948359012604, 0.5334170460700989, 0.44181737303733826] GRU: Mean Absolute Error: 0.2108 Root Mean Square Error: 0.5192 Mean Square Error: 0.2696
anomalies: (92, 10)
######################################################